package com.gjzhao.fmmall.service.juc;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Description: 测试 Callable 方式创建线程，接收返回值
 * @Author: gjzhao
 * @Date Created in 2022-03-06 10:56 下午
 */
public class TestCallableThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        //定义callable，创建线程
        Callable<Integer> callable = new Callable<Integer>() {

            @Override
            public Integer call() throws Exception {

                System.out.println("----进入线程:" + Thread.currentThread().getName());

                //回调逻辑
                return 555;
            }
        };

        //使用FutureTask包装callable
        FutureTask futureTask = new FutureTask(callable);
        //使用thread实例启动线程
        new Thread(futureTask,"t1").start();


        //获取回调结果:一般在主线程结束的时候调用get()，会阻塞，直到获取结果
        System.out.println("----线程执行结果：" + futureTask.get());

        System.out.println("-----main线程继续执行");

    }
}
